package com.yazif.vqa.api.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yazif.vqa.api.wechat.domain.TextMessage;
import com.yazif.vqa.api.wechat.service.WechatApiService;
import com.yazif.vqa.dao.RedisDao;
import com.yazif.vqa.domain.Deal;
import com.yazif.vqa.util.HttpUtils;
import com.yazif.vqa.util.RedisKeyUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@PropertySource("classpath:application.properties")
public class WechatApiServiceImpl implements WechatApiService, InitializingBean{

    @Resource
    private RedisDao redisDao;

    @Value("${spring.wechat.auth.appid}")
    private String appid;
    @Value("${spring.wechat.auth.appsecret}")
    private String appsecret;
    private static final String CUSTOM_SERVICE_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";

    private String ACCESS_TOKEN_URL;

    private static final String ACCESS_TOKEN_KEY = "access_token";
    private static final String ACCESS_EX_TIME = "expires_in";

    public String getAccessToken(){
        String key = RedisKeyUtil.getAccessTokenKey();
        String accessToken = null;

        accessToken = redisDao.get(key);
        if (accessToken == null){
            JSONObject jsonObject = HttpUtils.getMethod(ACCESS_TOKEN_URL);
            accessToken =  String.valueOf(jsonObject.get(ACCESS_TOKEN_KEY));
            String exiredStr = String.valueOf(jsonObject.get(ACCESS_EX_TIME));
            int expired = Integer.valueOf(exiredStr);
            if (accessToken != null){
                redisDao.set(key, expired, accessToken);
            }
        }
        return accessToken;
    }

    public void sendMessage(Deal deal){
        String access = getAccessToken();
        String url = CUSTOM_SERVICE_URL + access;
        TextMessage textMessage = new TextMessage();
        textMessage.setMsgtype("text");
        textMessage.setTouser(deal.getFromUser());
        textMessage.setText(deal.getAnswer());

        JSONObject jsonObject = HttpUtils.postMethod(url, JSON.toJSONString(textMessage));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appid + "&secret=" + appsecret;
    }
}
